<template>
<div>
    <el-container class="write-article">
      <el-breadcrumb separator-class="el-icon-arrow-right" style="margin-top: 10px; margin: 10px">
        <el-breadcrumb-item :to="{ path: '/home' }">论坛</el-breadcrumb-item>
        <el-breadcrumb-item>发布</el-breadcrumb-item>
      </el-breadcrumb>
      <el-header class="header" style="height: 40px">
        <el-select v-model="ForumAndTag.forum.type" placeholder="请选择文章专栏" style="width: 145px">
          <el-option v-for="(item,key) in types"
            :key="key"
            :label="item.type"
            :value="item.type"></el-option>
        </el-select>
        <el-input v-model="ForumAndTag.forum.title" placeholder="请输入标题..." style="width: 350px;margin-left: 10px"></el-input>
        <el-button class="button-new-tag" style="margin-left: 10px" type="primary" @click="addColumn">添加专栏</el-button>
        <el-select v-model="ForumAndTag.forum.source" placeholder="请选择文章类型" style="width: 145px;margin-left: 20px">
          <el-option value=1 label="原创"></el-option>
          <el-option value=0 label="转载"></el-option>
        </el-select>
        <el-input v-show="ForumAndTag.forum.source==='0'?true:false" v-model="ForumAndTag.forum.source_url" placeholder="请输入原文链接" style="width: 350px;margin-left: 10px"></el-input>
      </el-header>
      <el-main>
        <div id="editor">
            <mavon-editor
                v-model="ForumAndTag.forum.content"
                ref="md"
                @change="change"
                @imgAdd="$imgAdd"
                style="min-height: 550px; margin-bottom: 20px"/>
            <div style="display: flex">
              <el-input v-model="ForumAndTag.forum.description" type="textarea" placeholder="请输入论坛概要"></el-input>
              <el-upload
                class="upload-picture"
                action="http://localhost:8081/api/upload/picture"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
                :on-success="handleSuccess"
                multiple
                :limit="1"
                :on-exceed="handleExceed"
                :file-list="fileList">
                <el-button size="small" type="primary">点击上传论坛首图</el-button>
              </el-upload>
            </div>
        </div>
        <div style="display: flex;align-items: center;margin-top: 15px;justify-content: flex-end">
          <el-button @click="back">返回</el-button>
          <el-button type="success" @click="update(0)">保存</el-button>
          <el-button type="primary" @click="update(1)">修改</el-button>
        </div>
      </el-main>
    </el-container>
</div>
</template>

<script>
import { MessageBox } from 'element-ui'
import { mavonEditor } from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'
export default {
  components: {
    mavonEditor
  },
  data () {
    return {
      loading: false,
      html: '',
      content: '',
      fileList: [],
      ForumAndTag: {
        forum: {
          id: 0,
          uid: window.sessionStorage.getItem('uid'),
          username: window.sessionStorage.getItem('username'),
          title: '',
          published: '',
          content: '',
          create_time: null,
          mylike: 0,
          views: 0,
          type: '',
          commentable: 1,
          first_picture: null,
          description: '',
          source: '',
          source_url: null
        },
        tag_id: []
      },
      types: [],
      tags: []
    }
  },
  methods: {
    // 将图片上传到服务器，返回地址替换到md中
    $imgAdd (pos, $file) {
      const formdata = new FormData()
      formdata.append('file', $file)
      this.$axios.post('http://localhost:8081/api/upload/picture', formdata).then(res => {
        console.log(res.data)
        this.$refs.md.$img2Url(pos, res.data.data)
      }).catch(err => {
        console.log(err)
      })
    },
    change (value, render) {
      this.html = render
      this.ForumAndTag.forum.content = render
    },
    back () {
      this.$router.go(-1)
    },
    addColumn () {
      MessageBox.prompt('请输入专栏名称', '增加专栏', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        if (this.types.length > 100) {
          this.$message.error('专栏数量已达上限，无法添加')
        } else {
          var token = sessionStorage.getItem('token')
          this.$axios.defaults.headers.Authorization = 'Bearer ' + token
          this.$axios.post('/forum/addType', {
            type: value
          }).then(response => {
            if (response.data.code !== '200') this.$message.error('添加失败')
            else if (response.data.code !== '401') this.$message.error('请登录')
            else this.$message.success('添加成功')
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        })
      })
    },
    addTag () {
      MessageBox.prompt('请输入标签名称', '增加标签', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        if (this.tags.length > 100) {
          this.$message.error('标签数量已达上限，无法添加')
        } else {
          var token = sessionStorage.getItem('token')
          this.$axios.defaults.headers.Authorization = 'Bearer ' + token
          this.$axios.post('/forum/addTag', {
            tag: value
          }).then(response => {
            if (response.data.code !== '200') this.$message.error('添加失败')
            else this.$message.success('添加成功')
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        })
      })
    },
    getForum () {
      this.$axios.get('/other_forum/getMyForum', {
        params: {
          id: this.$route.params.id
        }
      }).then(response => {
        this.$set(this, 'ForumAndTag', response.data.data)
      })
    },
    update (published) {
      this.ForumAndTag.forum.published = published
      var token = sessionStorage.getItem('token')
      this.$axios.defaults.headers.Authorization = 'Bearer ' + token
      this.$axios.post('/other_forum/updateForum', this.ForumAndTag).then(response => {
        if (response.data.code !== '200') this.$message.error('修改失败')
        else if (response.data.code === '200') this.$message.success('修改成功!')
      })
    },
    getAllTags () {
      this.$axios.get('forum/getAllTags').then(response => {
        console.log(response.data)
        this.$set(this, 'tags', response.data.data)
      }).catch(error => {
        console.log(error)
      })
    },
    getAllTypes () {
      this.$axios.get('forum/getAllTypes').then(response => {
        console.log(response.data)
        this.$set(this, 'types', response.data.data)
      }).catch(error => {
        console.log(error)
      })
    },
    handleRemove (file, fileList) {
      console.log(file, fileList)
    },
    handlePreview (file) {
      console.log(file)
    },
    handleExceed (files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    beforeRemove (file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    handleSuccess (response, file, fileList) {
      this.ForumAndTag.forum.first_picture = response.data
    }
  },
  created () {
  },
  mounted () {
    this.getAllTags()
    this.getAllTypes()
    this.getForum()
  }
}
</script>

<style lang="less" scoped>
.el-main{
  padding: 10px;
}
</style>
